package net.kazed.nextaction.database.serialize;

import java.io.FileNotFoundException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;

import net.kazed.nextaction.database.GtdContext;

public class BackupFile {

   public void createBackup(Context context) {
      
      ContentResolver contentResolver = context.getContentResolver();
      DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-hh:mm");
      Date date = new Date();
      String fileName = "nextaction-backup-" + dateFormat.format(date) + ".nab";
      XmlWriter xmlWriter;
      try {
         xmlWriter = new XmlWriter(context.openFileOutput(fileName, Context.MODE_WORLD_WRITEABLE));
         xmlWriter.startElement("nextaction");
         xmlWriter.addElement("version", "0.6");
         xmlWriter.addElement("createdDate", dateFormat.format(date));
         
         ContextXmlSerializer serializer = new ContextXmlSerializer(xmlWriter);

         Cursor contextCursor = null;
         try {
            contextCursor = contentResolver.query(GtdContext.CONTENT_URI, GtdContext.FULL_PROJECTION.getFieldNames(), null,
                  null, GtdContext.ID + " ASC");
            contextCursor.moveToFirst();
            while (!contextCursor.isAfterLast()) {
               GtdContext gtdContext = new GtdContext(contextCursor);
               serializer.serialize(gtdContext);
            }
         } finally {
            try {
               contextCursor.close();
            } catch (Exception e) {

            }
         }
         xmlWriter.endElement();
         xmlWriter.flush();
      } catch (FileNotFoundException e) {
         throw new RuntimeException("Failed to open backup file");
      }

   }
}
